<?php

namespace app\api\controller;

use app\api\model\WxappPage;
use think\Db;
/**
 * 页面控制器
 * Class Index
 * @package app\api\controller
 */
class Page extends Controller
{
    /**
     * 页面数据
     * @param null $page_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($page_id = null)
    {
        // 页面元素
        $data = WxappPage::getPageData($this->getUser(false), $page_id);
        // dump($data);die;
        return $this->renderSuccess($data);
    }
    // 暂时使用
    public function syncDealerTree()
    {
        // 1. 读取原始推荐关系（一级）
        $refList = Db::name('dealer_referee')
            ->field('dealer_id, user_id, wxapp_id, create_time')
            ->select();

        // 2. 构建原始推荐图（dealer_id → user_id）
        $graph = [];
        foreach ($refList as $item) {
            $graph[$item['dealer_id']][] = [
                'user_id' => $item['user_id'],
                'wxapp_id' => $item['wxapp_id'],
                'create_time' => $item['create_time'],
            ];
        }

        // 3. 存储所有路径结果
        $result = [];

        // 4. 递归构造所有 ancestor → descendant 的路径
        $visited = [];
        foreach ($graph as $root => $children) {
            $this->dfsBuild($root, $root, 1, $graph, $result, $visited);
        }

        // 5. 写入数据库前清空旧数据（可选）
        Db::name('dealer_relation_tree')->delete(true); // TRUNCATE 操作

        // 6. 批量写入
        $chunks = array_chunk($result, 1000); // 分批写入防止过大
        foreach ($chunks as $chunk) {
            Db::name('dealer_relation_tree')->insertAll($chunk);
        }

        return $this->renderSuccess("同步完成，共写入 " . count($result) . " 条记录");
    }

    // 递归构建路径：从 $ancestor 开始，构造所有 descendant
    private function dfsBuild($ancestor, $current, $depth, &$graph, &$result, &$visited, $wxapp_id = 10001)
    {
        if (!isset($graph[$current])) {
            return;
        }

        foreach ($graph[$current] as $child) {
            $descendant = $child['user_id'];

            // 防止环形引用
            $key = $ancestor . '_' . $descendant;
            if (isset($visited[$key])) {
                continue;
            }
            $visited[$key] = true;

            // 记录一条路径
            $result[] = [
                'ancestor_user_id' => $ancestor,
                'descendant_user_id' => $descendant,
                'depth' => $depth,
                'wxapp_id' => $child['wxapp_id'],
                'create_time' => $child['create_time'],
            ];

            // 递归向下
            $this->dfsBuild($ancestor, $descendant, $depth + 1, $graph, $result, $visited, $child['wxapp_id']);
        }
    }

}
